import { onHide } from '@dcloudio/uni-app';
<!--
 * @Description:
 * @Date: 2024-05-14 09:00:16
 * @LastEditTime: 2024-08-26 16:54:49
-->
<route lang="json5" type="login">
{
  style: {
    navigationBarTitleText: '电子送达',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="w-screen h-screen flex flex-col">
    <view class="delivery-header p-20rpx bg-#fff">
      <wd-search
        v-model="queryParams.acceptName"
        placeholder="请输入被送达人姓名"
        cancel-txt="搜索"
        @blur="change"
        v-if="userStore.userInfo.currentRole == 'leader'"
      />
      <wd-radio-group
        v-model="queryParams.time"
        @change="changeGroup"
        shape="button"
        class="flex justify-between"
      >
        <wd-radio :value="1">全部</wd-radio>
        <wd-radio :value="2">近一周</wd-radio>
        <wd-radio :value="3">近一个月</wd-radio>
        <wd-radio :value="4">近三个月</wd-radio>
      </wd-radio-group>
      <view class="mt-20rpx" v-if="userStore.userInfo.currentRole == 'leader'">
        <wd-picker
          :columns="promotionlist"
          @confirm="radioChange"
          v-model="queryParams.fileType"
          use-default-slot
        >
          <view class="flex items-center">
            <view class="text-#828282 text-30rpx">文件类型：</view>
            <view
              class="flex gap-10rpx justify-center items-center px-20rpx py-10rpx border-rd-10rpx border-solid border-2rpx border-#bbbbbb"
            >
              <tex class="text-28rpx">
                {{ queryParams.fileType ? getType(queryParams.fileType) : '请选择' }}
              </tex>
              <wd-icon name="arrow-down" color="#888888" size="20px"></wd-icon>
            </view>
          </view>
        </wd-picker>
      </view>
    </view>
    <view class="w-100% flex-1 bg-#F4F5F9 px-30rpx pt-40rpx box-border">
      <view
        class="flex mb-20rpx flex-col px-40rpx py-10rpx justify-center overflow-hidden bg-#fff"
        v-for="item in electronicList"
        :key="item.id"
        @click="handelDetails(item.id)"
      >
        <view class="py-10rpx flex justify-between border-b-2rpx border-b-solid border-b-#EEEEEE">
          <text class="text-28rpx text-#999999">送达文号</text>
          <text class="text-28rpx text-#474747">{{ item.number }}</text>
        </view>
        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">文件类型</text>
          <text class="text-28rpx text-#474747">{{ promotionlist[item.fileType].label }}</text>
        </view>

        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">被送达人姓名</text>
          <text class="text-28rpx text-#474747">{{ item.acceptName }}</text>
        </view>
        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">被送达人身份证号</text>
          <text class="text-28rpx text-#474747">{{ item.acceptCard }}</text>
        </view>
        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">被送达人联系方式</text>
          <text class="text-28rpx text-#474747">{{ item.acceptPhone }}</text>
        </view>
        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">案件名称</text>
          <text class="text-28rpx text-#474747">{{ item.caseNumber }}</text>
        </view>
        <view class="py-10rpx flex justify-between">
          <text class="text-28rpx text-#999999">送达时间</text>
          <text class="text-28rpx text-#474747">
            {{ formatTime(item.createTime, 'yyyy-MM-dd HH:mm:ss') }}
          </text>
        </view>
        <view
          class="pt-10rpx pb-20rpx flex justify-between border-b-2rpx border-b-solid border-b-#EEEEEE"
        >
          <text class="text-28rpx text-#999999">签收状态</text>
          <text
            class="text-28rpx text-#117B28 bg-#E4FFF0 px-30rpx py-10rpx border-rd-10rpx"
            v-if="item.status"
          >
            已签收
          </text>
          <text class="text-28rpx text-#E0400F bg-#FFEAE4 px-30rpx py-10rpx border-rd-10rpx" v-else>
            待签收
          </text>
        </view>
        <view
          v-if="
            userStore.userInfo.currentRole == 'leader' ||
            (userStore.userInfo.currentRole != 'leader' && item.status)
          "
          @click.stop="handelDetails(item.id)"
          class="py-20rpx flex justify-center color-#64769D"
        >
          查看详情
        </view>
        <view
          v-if="userStore.userInfo.currentRole != 'leader' && !item.status"
          @click.stop="handelSign(item.id)"
          class="w-max mx-auto my-10rpx py-15rpx flex justify-center border-rd-10rpx bg-#0064B7 px-20rpx py-10rpx color-#fff"
        >
          前往签收
        </view>
      </view>
      <view v-if="electronicList.length <= 0">
        <wd-status-tip image="message" tip="暂无数据！" />
      </view>
    </view>

    <wd-loadmore v-if="electronicList.length > 0" :state="state" @reload="loadmore" />
    <wd-fab
      v-if="userStore.userInfo.currentRole == 'leader'"
      v-model:active="disabled"
      type="primary"
      position="right-bottom"
      direction="left"
    ></wd-fab>
  </view>
</template>

<script setup lang="ts">
import { getElectronicAPI } from '@/service/index/foo'
import { formatTime } from '@/utils/index'
import { useUserStore } from '@/store'
const userStore = useUserStore()
const pages = reactive({
  pageNo: 1,
  pageSize: 10,
})
const state = ref<string>('loading')
const num = ref<number>(0)
const max = ref<number>(60)
const queryParams = reactive({
  fileType: '',
  acceptName: '',
  creator: undefined,
  acceptPhone: undefined,
  time: 1,
  createTime: [],
})
const electronicList = ref([])
const { safeAreaInsets } = uni.getSystemInfoSync()
const disabled = ref<boolean>(false)
const promotionlist = ref<any[]>([
  {
    value: '',
    label: '全部',
  },
  {
    value: '1',
    label: '起诉书',
  },
  {
    value: '2',
    label: '抗诉书',
  },
  {
    value: '3',
    label: '补充侦查决定书',
  },
  {
    value: '4',
    label: '证据清单',
  },
  {
    value: '5',
    label: '传票',
  },
  {
    value: '6',
    label: '量刑建议书',
  },
  {
    value: '7',
    label: '申诉复查决定书',
  },
  {
    value: '8',
    label: '检察建议书',
  },
  {
    value: '9',
    label: '其他',
  },
])
onShow(() => {
  pages.pageNo = 1
  electronicList.value = []
  if (userStore.userInfo.currentRole == 'leader') {
    queryParams.creator = userStore.userInfo.userId
  } else {
    queryParams.acceptPhone = userStore.userInfo.phone
  }
  disabled.value = false
  getList()
})
onReachBottom(() => {
  if (electronicList.value.length === max.value) {
    state.value = 'finished'
  } else if (electronicList.value.length < max.value) {
    pages.pageNo += 1
    loadmore()
  }
})
function loadmore() {
  state.value = 'loading'
  setTimeout(() => {
    getList()
  }, 1000)
}
onPullDownRefresh(async () => {
  pages.pageNo = 1
  electronicList.value.length = 0
  await getList()
  uni.stopPullDownRefresh()
})
function change() {
  pages.pageNo = 1
  electronicList.value = []
  getList()
}
function radioChange() {
  pages.pageNo = 1
  electronicList.value = []
  getList()
}
function getList() {
  getElectronicAPI({ ...pages, ...queryParams, time: undefined }).then((res) => {
    electronicList.value.push(...res.data.list)
    max.value = res.data.total
    electronicList.value.length == max.value
      ? (state.value = 'finished')
      : (state.value = 'loading')
  })
}
const getType = computed(() => {
  return function (index) {
    if (index != undefined) {
      return promotionlist.value.filter((item) => {
        return item.value == index
      })[0].label
    }
  }
})
const handelClick = () => {
  console.log(212121)
}
const changeGroup = () => {
  pages.pageNo = 1
  electronicList.value = []
  if (queryParams.time === 2) {
    const weekRange = getCurrentToPreviousDateTimeRange('week')
    queryParams.createTime = [weekRange.end, weekRange.start]
  } else if (queryParams.time === 3) {
    const monthRange = getCurrentToPreviousDateTimeRange('month')
    queryParams.createTime = [monthRange.end, monthRange.start]
  } else if (queryParams.time === 4) {
    const halfYearRange = getCurrentToPreviousDateTimeRange('halfYear')
    queryParams.createTime = [halfYearRange.end, halfYearRange.start]
  } else {
    queryParams.createTime = []
  }
  getList()
}
watch(disabled, (newVal) => {
  if (newVal) {
    uni.navigateTo({ url: '/pages/ElectronicDelivery/ElectronicDeliverySub' })
  }
})
const handelDetails = (id) => {
  uni.navigateTo({ url: `/pages/ElectronicDelivery/ElectronicDeliveryDetails?id=${id}` })
}
const handelSign = (id) => {
  uni.navigateTo({ url: `/pages/ElectronicDelivery/ElectronicDeliverySign?id=${id}` })
}
function getCurrentToPreviousDateTimeRange(interval) {
  // 获取当前时间
  const currentDateTime = new Date()
  // 根据传入的间隔计算之前的时间
  let previousDateTime
  switch (interval) {
    case 'week':
      previousDateTime = new Date(currentDateTime - 7 * 24 * 60 * 60 * 1000)
      break
    case 'month':
      previousDateTime = new Date(
        currentDateTime.getFullYear(),
        currentDateTime.getMonth() - 1,
        currentDateTime.getDate(),
      )
      break
    case 'halfYear':
      previousDateTime = new Date(
        currentDateTime.getFullYear(),
        currentDateTime.getMonth() - 3,
        currentDateTime.getDate(),
      )
      break
    case 'year':
      previousDateTime = new Date(
        currentDateTime.getFullYear() - 1,
        currentDateTime.getMonth(),
        currentDateTime.getDate(),
      )
      break
    default:
      throw new Error('Invalid interval')
  }

  // 格式化日期时间为YYYY-MM-DD HH:mm:ss格式
  function formatDateTime(dateTime) {
    const year = dateTime.getFullYear()
    const month = (1 + dateTime.getMonth()).toString().padStart(2, '0')
    const day = dateTime.getDate().toString().padStart(2, '0')
    const hours = dateTime.getHours().toString().padStart(2, '0')
    const minutes = dateTime.getMinutes().toString().padStart(2, '0')
    const seconds = dateTime.getSeconds().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 返回时间区间
  return {
    start: formatDateTime(currentDateTime),
    end: formatDateTime(previousDateTime),
  }
}
</script>
<style lang="scss" scoped>
::v-deep .wd-radio-group {
  display: flex;
  justify-content: space-between;
}
::v-deep .wd-radio__label {
  background: #fff !important;
  border: 2rpx solid #bbbbbb !important;
  border-radius: 10rpx !important;
}
::v-deep .is-checked > .wd-radio__label {
  background: #0063af !important;
  color: #fff !important;
  border: none !important;
}
</style>
